package com.gy.yemall.yemallproduct.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.gy.common.constant.ProductConstant;
import com.gy.common.to.BoundsTo;
import com.gy.common.to.SkuHasStock;
import com.gy.common.to.SkuReductionTo;
import com.gy.common.to.es.SkuEsModel;
import com.gy.common.utils.R;
import com.gy.yemall.yemallproduct.entity.*;
import com.gy.yemall.yemallproduct.entity.vo.*;
import com.gy.yemall.yemallproduct.feign.CouponFeignService;
import com.gy.yemall.yemallproduct.feign.EsSearchSerivce;
import com.gy.yemall.yemallproduct.feign.WareSkuFeignService;
import com.gy.yemall.yemallproduct.service.*;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gy.common.utils.PageUtils;
import com.gy.common.utils.Query;

import com.gy.yemall.yemallproduct.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDao spuInfoDao;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareSkuFeignService wareSkuFeignService;

    @Autowired
    private EsSearchSerivce esSearchSerivce;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }
    // TODO
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        /**
         * 1. 保存spu基本信息 pms_spu_info
         * 2. 保存spu的描述图片 pms_spu_info_desc
         * 3. 保存spu的图片集  pms_spu_images
         * 4. 保存spu的规格参数 pms_product_attr_value
         * 5. 保存spu的积分信息 sms_spu_bounds
         * 6. 保存当前spu对应的所有的 sku 的信息
         * 6.1) sku的基本信息 pms_sku_info
         * 6.2) sku的图片信息 pms_sku_images
         * 6.3) sku的销售属性信息 pms_sku_sale_attr_value
         * 6.4) sku的优惠、 满减信息 sms_sku_full_reduction / sms_member_price / sms_sku_ladder
         */
        // 1. 保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        spuInfoDao.insert(spuInfoEntity);

        // 2. 保存spu的描述图片 pms_spu_info_desc spu_id在pms_spu_info这张表中
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        List<String> decript = spuSaveVo.getDecript();
        // 利用逗号进行分割
        spuInfoDescEntity.setDecript(String.join("," , decript));
        spuInfoDescService.save(spuInfoDescEntity);

        // 3. 保存spu的图片集  pms_spu_images
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        // 4. 保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map((attr) -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrId(attr.getAttrId());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            AttrVo infoBy = attrService.getInfoBy(attr.getAttrId());
            productAttrValueEntity.setAttrName(infoBy.getAttrName());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(collect);


        // 5. 保存spu的积分信息 sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        BoundsTo boundsTo = new BoundsTo();
        BeanUtils.copyProperties(bounds, boundsTo);
        boundsTo.setSpuId(spuInfoEntity.getId());
        couponFeignService.saveBounds(boundsTo);


        List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach((item) -> {
                // 获取默认的图片
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }

                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                // 6.1) sku的基本信息 pms_sku_info
                skuInfoService.save(skuInfoEntity);

                // 6.2) sku的图片信息 pms_sku_images
                List<SkuImagesEntity> collect1 = item.getImages().stream().map((img) -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).collect(Collectors.toList());

                skuImagesService.saveBatch(collect1);

                // 6.3) sku的销售属性信息 pms_sku_sale_attr_value
                List<SkuSaleAttrValueEntity> collect2 = item.getAttr().stream().map((attr) -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(collect2);

                /**
                 * 6.4) sku的优惠、 满减信息
                 * sms_sku_full_reduction
                 * sms_member_price
                 * sms_sku_ladder
                 */
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                couponFeignService.saveSkuReduction(skuReductionTo);
            });
        }
    }

    @Override
    public PageUtils queryPageCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        String catelogId = (String) params.get("catelogId");
        String brandId = (String) params.get("brandId");
        String status = (String) params.get("status");

        if (!StringUtils.isEmpty(key)) {
            // 使用and代表条件是写在括号里面的
            queryWrapper.and((wrapper) -> {
               wrapper.eq("id", key).or().eq("spu_name", key);
            });
        }

        if (!StringUtils.isEmpty(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }

        if (!StringUtils.isEmpty(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }

        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("publish_status", status);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void upSku(Long spuId) {
        // 1.查出当前spuId对应的sku的信息,sku_info表
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkuBySpuId(spuId);
        // 快速获取出所有的skuIds集合
        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        // 根据spuId查出对应的所有属性pms_attr_attrgroup_relation
        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.listForSku(spuId);
        // 得出该spuId对应的所有属性的id
        List<Long> attrIds = productAttrValueEntities.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        // 根据所有的属性id进行查属性表
        List<Long> searchAttrIds = attrService.queryByAttrIds(attrIds);

        Set<Long> set = new HashSet<>(searchAttrIds);
        // 查询全部的属性id是否在查出来的里面
        List<SkuEsModel.Attrs> collect = productAttrValueEntities.stream().filter(item -> {
            return set.contains(item.getAttrId());
        }).map((item) -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());

        Map<Long, Boolean> collect1 = null;
        try {
            // 远程调用获取库存
            R skusHasStock = wareSkuFeignService.getSkusHasStock(skuIds);
            TypeReference<List<SkuHasStock>> typeReference = new TypeReference<List<SkuHasStock>>(){};
            List<SkuHasStock> data = skusHasStock.getData(typeReference);
            // 将getSkuId作为key ，value用getHasStock
            collect1 = data.stream().collect(Collectors.toMap(SkuHasStock::getSkuId, SkuHasStock::getHasStock));
        } catch (Exception e) {
            log.error("远程调用wareSkuFeignService失败");
        }
        Map<Long, Boolean> finalCollect = collect1;
        List<SkuEsModel> skuEsModelLists = skuInfoEntities.stream().map((skuInfoEntity -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity, skuEsModel);
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());
            // 设置品牌的名称
            BrandEntity byId = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(byId.getName());
            skuEsModel.setBrandImg(byId.getLogo());
            // 设置分类的名称
            CategoryEntity byId1 = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(byId1.getName());
            // 对Attrs进行赋值
            skuEsModel.setAttrs(collect);

            // 需要调用远程服务进行获取
            if (finalCollect == null) {
                // 默认有库存
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalCollect.get(skuInfoEntity.getSkuId()));

            }
            skuEsModel.setHotScore(0L);

            return skuEsModel;
        })).collect(Collectors.toList());

        // TODO 远程将skuEsModelLists数据发送给全文检索服务
        R r = esSearchSerivce.productStatusUp(skuEsModelLists);
        Integer code = (Integer) r.get("code");
        System.out.println(code);
        if (code == 0) {
            // 远程接口调用成功, 需要修改状态 ,修改spu的状态
            baseMapper.updateStatusBySpuId(spuId, ProductConstant.StatusEnum.UP_STATUS.getCode());
        } else {
            log.error("修改商品状态失败");
        }
    }

}